<template>
  <div style="height:100%;background-color: #fff;">

    <Layout>
      <!-- 左侧表格 -->
      <div id="leftTab" style="width:320px">
        <div class="toolsLeft">
          <!-- 功能按钮组 高度30px-->
          <div class="buttonbg">
            <a class="bd_bgi">
              <span class="add"></span>
              <span class="text" @click="addPoint">添加</span>
            </a>
            <a class="bd_bgi">
              <span class="modify"></span>
              <span class="text" @click="modifyPoint">修改</span>
            </a>
            <a class="bd_bgi">
              <span class="delete"></span>
              <span class="text" @click="deletePoint">删除</span>
            </a>
            <a class="bd_bgi">
              <span class="closed" @click="closeSelf"></span>
              <span class="text" @click="closeSelf">关闭</span>
            </a>
          </div>
        </div>

        <div style="position: absolute;top:38px;left: 10px;right: 10px;">

          <SearchBox
            style="width:100%;"
            placeholder="请输入考勤点名称"
            v-model="serchTxt"
            @search="loadDataLeft($event)"
            @keydown="searchEnter"
          >
            <Addon>
            <span
              v-if="serchTxt"
              class="textbox-icon icon-clear"
              title="Clear value"
              @click="serchTxt = ''"
            ></span>
            </Addon>
          </SearchBox>
        </div>

        <!-- 左侧表格 -->
        <div class="tableContentL grid-wrapper" style="top:70px">
          <!-- AgGridVue   -->
          <ag-grid-vue
            id="myGrid"
            ref="myGrid"
            style="width: 100%; height: 100%;text-align: center;"
            class="ag-theme-balham"
            :gridOptions="gridOptions"
            :columnDefs="columnDefs"
            rowSelection="multiple"
            :rowDeselection="true"
            @rowClicked="rowClickedd"
            @grid-ready="onGridReady"
            :rowData="rowData"
            :defaultColDef="defaultColDef"
            :localeText="localeText"
            :rowDragManaged="true"
            :animateRows="true"
          ></ag-grid-vue>
        </div>
      </div>

      <!-- 右侧 -->
      <LayoutPanel region="center" class="cont LayoutPanelRight" style="left: 320px">
        <div class="content">
          <!-- 表格以外的高度，计算时减去tools的实际高度 -->
          <div id="tools">
            <!-- 功能按钮组 -->
            <div class="buttonbg">
              <a class="bd_bgi">
                <span class="import"></span>
                <span class="text" @click="newlink">打开新链接</span>
              </a>

              <div class="page-title">实时考勤管理系统 > 打卡点设置</div>
            </div>
            <!-- 查询条件组 -->
            <div class="conditions">

              <div class="marginBottom8">
                <Label>详细地址：</Label>
                <input :value="form.address" type="text" id="suggestId"
                       style="width: 500px;height: 24px;margin-top: 3px;"/>
              </div>

              <!--<div class="marginBottom8">-->
              <!--<Label></Label>-->
              <!--<LinkButton class="startSerch" @click="querySearchAsync">开始查询</LinkButton>-->
              <!--</div>-->

            </div>
          </div>

          <!-- 右侧表格容器 -->
          <div id="tableContent" style="overflow: auto;">
            <div id="map-container" :style="mapBoxStyle"/>

            <!--底部填写组-->
            <div style="padding: 10px 15px;" id="bottomInput">
              <div class="marginRight15">
                <Label align="right">经度</Label>
                <TextBox
                  :disabled="textBoxDisabled"
                  class="textBox200"
                  v-model="form.addrPoint.lng"
                  placeholder="请输入经度"
                  @valueChange="valueChange"
                ></TextBox>
              </div>
              <div class="marginRight15">
                <Label align="right">纬度</Label>
                <TextBox
                  :disabled="textBoxDisabled"
                  class="textBox200"
                  v-model="form.addrPoint.lat"
                  placeholder="定输入纬度"
                  @valueChange="valueChange"
                ></TextBox>
              </div>
              <div class="marginRight15">
                <Label align="right">考勤点名称</Label>
                <TextBox
                  :disabled="textBoxDisabled"
                  class="textBox200"
                  v-model="form.attendancePoint"
                  placeholder="请输入考勤点名称"
                  @valueChange="valueChange"
                ></TextBox>
              </div>
              <div class="marginRight15" style="margin-right: 0;">
                <Label align="right">范围(米)</Label>
                <TextBox
                  :disabled="textBoxDisabled"
                  class="unifiedWid"
                  v-model="form.range"
                  placeholder="请输入整数数字"
                  @valueChange="valueChange"
                ></TextBox>
              </div>
              <div class="marginRight15">
                <Label></Label>
                <LinkButton class="startSerch" @click="onSubmit" :disabled="btndisabled" v-if="isNew == 1">添加</LinkButton>
                <LinkButton class="startSerch" @click="onModify" :disabled="btndisabled" v-else>修改</LinkButton>
              </div>
              <div id="result"></div>
            </div>
          </div>

        </div>

      </LayoutPanel>
    </Layout>

  </div>
</template>

<script>
  /* eslint-disable */
  // import loadBMap from '@/api/loadBMap.js'
  import BMap from 'BMap'
  import mapSetApi from "@/api/mapSet";
  import {tableBoxHeight} from "@/api/communal";
  import {AgGridVue} from "ag-grid-vue";
  import language_ag from "@/config/localization_ag"; //表格插件汉化

  export default {
    components: {
      AgGridVue
    },
    data() {
      return {
        mapBoxStyle:{
          width:"100%",
          height:"400px"
        },
        gridOptions: null,
        gridApi: null,
        columnApi: null,
        defaultColDef: null, //配置信息
        columnDefs: null, //左侧表格表头
        rowData: [], //左侧表格数据
        selectedRowDataUp: null, //左侧表格行数据
        localeText: language_ag, // ag-grid汉化
        serchTxt: "", //查询值
        btndisabledNo: 1,
        isNew: 1,
        form: {
          address: '', // 详细地址
          addrPoint: { // 详细地址经纬度
            lng: "",
            lat: ""
          },
          attendancePoint: '', // 考勤点名称
          range: "100", // 范围
        },
        btndisabled: true, // 禁用按钮
        textBoxDisabled: true, // 禁用按钮
        addressData: [],
        map: '', // 地图实例
        mk: '', // Marker实例
        point: '',
        locationPoint: null,
        plyy: null,
        initcity: null,
      }
    },
    beforeMount() {
      this.gridOptions = {};

      this.columnDefs = [
        {
          headerName: "编号",
          field: "bh",
          width: 80,
          minWidth: 80,
        },
        {
          headerName: "考勤点名称",
          field: "mc",
          width: 160,
          minWidth: 160,
        },
        {
          headerName: "经度",
          field: "longitude",
          width: 100,
          minWidth: 100,
        },
        {
          headerName: "纬度",
          field: "latitude",
          width: 100,
          minWidth: 100,
        },
        {
          headerName: "范围",
          field: "cardRange",
          width: 80,
          minWidth: 80,
        }
      ];

      // this.rowData = [];

      this.defaultColDef = {
        //默认渲染配置
        editable: false, //为true全部表格可编辑
        resizable: false, //可否拖动列
        sortable: false, //可否排序
        filter: false, //是否可过滤
        colResizeDefault: "shift", //列移位
        //单元格样式
        cellStyle: {"border-right": "1px solid #d9dcde"},
        flex: 1
      };
    },
    mounted() {
      tableBoxHeight();
      // await loadBMap('htgznmBQ0fTOjLFTz98yrUb5IiABdXOG'); // 加载引入BMap
      let Height = document.getElementById("tableContent");
      let bottomInput = document.getElementById("bottomInput");
      this.mapBoxStyle.height = Height.offsetHeight - bottomInput.offsetHeight - 30  + "px";

      // try {
      //   let fatherURL = window.opener.document.URL;
      //   console.log(fatherURL);
      //   if (fatherURL.indexOf('cnsvwshvm12124.csvw.com') > -1){
      //     console.log("可以继续");
      //   } else {
      //     console.log("你没有权限1");
      //     // this.closeSelf();
      //     // return
      //   }
      // } catch (e) {
      //   console.log("你没有权限2");
      //   // this.closeSelf();
      //   // return
      // }
      //
      // let fatherURL2 = window.opener.document.URL;
      // console.log(fatherURL2);


      this.initMap();
      this.loadDataLeft();
    },
    methods: {
      valueChange() {
        let point = this.form.attendancePoint.replace(/\s*/g, "");
        let range = this.form.range.replace(/\s*/g, "");
        let lng = this.form.addrPoint.lng.replace(/\s*/g, "");
        let lat = this.form.addrPoint.lat.replace(/\s*/g, "");
        if (point != "" && range != "" && lng != "" && lat != "" && this.btndisabledNo == 1) {
          this.btndisabled = false;
        } else {
          this.btndisabled = true;
        }

      },
      closeSelf(){
        if (navigator.userAgent.indexOf('MSIE') > 0) { // close IE
          if (navigator.userAgent.indexOf('MSIE 6.0') > 0) {
            window.opener = null;
            window.close();
          } else {
            window.open('', '_top');
            window.top.close();
          }
        } else { // close chrome;It is effective when it is only one.
          window.opener = null;
          window.open('', '_self');
          window.close();
        }
      },

      // 初始化地图
      initMap() {
        var that = this;
        // 1、挂载地图
        this.map = new BMap.Map('map-container');
        this.map.centerAndZoom("上海市嘉定区上汽大众汽车办公楼2期", 18);
        // 根据给定地址初始化定位点并标注
        var myGeo = new BMap.Geocoder();
        // 将地址解析结果显示在地图上，并调整地图视野
        myGeo.getPoint('上海市嘉定区上汽大众汽车办公楼2期', function(point){
          if(point){
            that.map.centerAndZoom(point, 18);
            that.map.panTo(point);
            //创建圆打卡范围
            that.greatCircle(point);
            that.mk = new BMap.Marker(point, {enableDragging: true});
            that.map.addOverlay(that.mk);
          }else{
            // alert('您选择的地址没有解析到结果！');
          }
        }, '上海市');

        // 2、获取当前城市,网络自动定位不准确，改为使用上面固定地址定位
        // var myCity = new BMap.LocalCity();
        // myCity.get(function (res) {
        //   // console.log(res);
        //   // alert(data.name);
        //   // data.center: {lng: 121.48023738884737, lat: 31.236304654494646, Ye: "inner"}
        //   // data.code : 289
        //   // data.level : 12
        //   // data.name : "上海市"
        //   that.point = new BMap.Point(res.center.lng, res.center.lat);
        //   that.map.centerAndZoom(that.point, 18);
        //   that.mk = new BMap.Marker(that.point, {enableDragging: true});
        //   that.map.addOverlay(that.mk);
        //   that.map.panTo(that.point);
        //   //创建圆打卡范围--测试
        //   that.greatCircle(that.point);
        //   that.mk.addEventListener('dragend', function (e) {
        //     that.getAddrByPoint(e.point);
        //   });
        // });
        this.map.enableScrollWheelZoom(); //开启滚动缩放
        this.map.enableContinuousZoom(); //开启缩放平滑

        var ac = new BMap.Autocomplete(    //建立一个自动完成的对象
          {
            "input": "suggestId"
            , "location": this.map
          });
        ac.addEventListener("onhighlight", function (e) {  //鼠标放在下拉列表上的事件
          var str = "";
          var _value = e.fromitem.value;
          var value = "";
          if (e.fromitem.index > -1) {
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
          }
          str = "FromItem<br />index = " + e.fromitem.index + "<br />value = " + value;

          value = "";
          if (e.toitem.index > -1) {
            _value = e.toitem.value;
            value = _value.province + _value.city + _value.district + _value.street + _value.business;
          }
          str += "<br />ToItem<br />index = " + e.toitem.index + "<br />value = " + value;
        });

        ac.addEventListener("onconfirm", function (e) {    //鼠标点击下拉列表后的事件
          // console.log(e.item);
          var _value = e.item.value;
          that.form.address = _value.province + _value.city + _value.district + _value.street + _value.business;
          that.setPlace();
        });

        // 3、设置图像标注并绑定拖拽标注结束后事件--移动到获取城市的方法里了
        // this.mk = new BMap.Marker(point, { enableDragging: true });
        // this.map.addOverlay(this.mk);
        // this.mk.addEventListener('dragend', function(e) {
        //     that.getAddrByPoint(e.point);
        // });

        //初始化范围多边形--测试
        // this.polygon();

        // 判断点击处是否在圆内
        // this.mk.addEventListener('click', this.overlayStyle);


        // 4、添加（右上角）平移缩放控件
        this.map.addControl(new BMap.NavigationControl({
          anchor: BMAP_ANCHOR_TOP_RIGHT,
          type: BMAP_NAVIGATION_CONTROL_SMALL
        }))

        // 5、添加（右下角）定位控件
        // var geolocationControl = new BMap.GeolocationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT});
        // geolocationControl.addEventListener('locationSuccess', function (e) {
        //   // console.log(e);
        //   that.getAddrByPoint(e.point)
        // })
        // geolocationControl.addEventListener('locationError', function (e) {
        //   // alert(e.message)
        // })
        // this.map.addControl(geolocationControl);

        // 6、浏览器定位
        // this.geolocation();

        // 7、绑定点击地图任意点事件
        this.map.addEventListener('click', function (e) {
          that.getAddrByPoint(e.point);
          // that.overlayStyle(e.point);
        })
      },
      // 获取两点间的距离
      getDistancs(pointA, pointB) {
        return this.map.getDistance(pointA, pointB).toFixed(2)
      },
      // 浏览器定位函数
      geolocation() {
        var that = this
        var geolocation = new BMap.Geolocation()
        geolocation.getCurrentPosition(function (res) {
          // console.log(res);
          if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            that.getAddrByPoint(res.point)
            that.locationPoint = res.point
          } else {
            // alert('浏览器failed' + this.getStatus())
            that.locationPoint = new BMap.Point(113.3324436, 23.1315381)
          }
        }, {enableHighAccuracy: true})
      },
      // 2、逆地址解析函数
      getAddrByPoint(point) {
        var that = this;
        that.map.clearOverlays();
        that.map.centerAndZoom(point);
        that.mk = new BMap.Marker(point, {enableDragging: true});
        that.map.addOverlay(that.mk);
        var geco = new BMap.Geocoder();
        geco.getLocation(point, function (res) {
          console.log(res);
          that.mk.setPosition(point);
          that.map.panTo(point);
          that.form.address = res.address;
          that.form.addrPoint.lng = point.lng + "";
          that.form.addrPoint.lat = point.lat + "";
          // that.form.addrPoint = point;
          // that.InOrOutPolygon(point.lng, point.lat);
        });
        //创建圆打卡范围
        that.greatCircle(point);
      },
      // 8-1、地址搜索
      querySearchAsync(str, cb) {
        var that = this;
        var options = {
          onSearchComplete: function (res) {
            var s = []
            if (local.getStatus() == BMAP_STATUS_SUCCESS) {
              for (var i = 0; i < res.getCurrentNumPois(); i++) {
                s.push(res.getPoi(i))
              }
            }
            that.addressData = s;
            console.log(that.addressData);
          }
        }
        var local = new BMap.LocalSearch(this.map, options)
        local.search(this.form.address)
      },
      // 8-2、选择地址
      handleSelect(item) {
        this.form.address = item.address + item.title;
        // this.form.addrPoint = item.point;
        this.form.addrPoint.lng = point.lng + "";
        this.form.addrPoint.lat = point.lat + "";
        this.map.clearOverlays();
        this.mk = new BMap.Marker(item.point);
        this.map.addOverlay(this.mk);
        this.map.panTo(item.point);
      },
      // 创建圆
      greatCircle(point) {
        let that = this;
        let range = (this.form.range == "" || this.form.range == null) ? 100:this.form.range;
        that.circle = new BMap.Circle(point, range, {
          fillColor: "blue",    //圆形填充颜色
          strokeWeight: 1,    //圆形边线宽度，大于1的整数
          fillOpacity: 0.3,   //圆形填充的透明度
          strokeOpacity: 0.3 //圆形边线透明度
        });
        this.map.addOverlay(that.circle);
        // circle.addEventListener('click', this.overlayStyle);

      },
      // 获取覆盖物属性,点击的点是否在范围内--测试
      overlayStyle(e) {
        var that = this;
        console.log(e.target);
        var p = e.target;
        if (p instanceof BMap.Marker) {
          console.log('该覆盖物是点，点的坐标为：' + p.getPosition().lng + ',' + p.getPosition().lat);
        } else if (p instanceof BMap.Circle) {
          console.log('该覆盖物是圆，其半径为：' + p.getRadius() + '圆中心点坐标：' + p.getCenter().lng + ',' + p.getCenter().lat);
        } else {
          console.log('无法获知该覆盖物类型');
        }

      },

      setPlace() {
        let that = this;
        that.map.clearOverlays();    //清除地图上所有覆盖物
        function myFun() {
          var pp = local.getResults().getPoi(0).point;    //获取第一个智能搜索的结果
          that.form.addrPoint.lng = pp.lng + "";
          that.form.addrPoint.lat = pp.lat + "";
          that.map.centerAndZoom(pp);
          that.map.panTo(pp);
          that.map.addOverlay(new BMap.Marker(pp));    //添加标注
          //创建圆打卡范围
          that.greatCircle(pp);
        }

        var local = new BMap.LocalSearch(that.map, { //智能搜索
          onSearchComplete: myFun
        });
        local.search(that.form.address);
      },

      // 根据考勤点名称
      loadDataLeft() {
        let param = {
          pageNumber: 1,
          pageSize: 2000,
          serchTxt: this.serchTxt,
        };
        this.getCalendarList(param);
        this.selectedRowDataUp = null;
      },
      // 获取考勤点列表
      async getCalendarList(param) {
        let res = await mapSetApi.getDzStDeviceList(param);
        // console.log(res);
        if (res.success) {
          this.rowData = res.result.records;
        } else {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: res.message
          });
        }
      },

      clearMsg() {
        this.form.attendancePoint = "";
        this.form.range = "100";
        this.form.addrPoint.lng = "";
        this.form.addrPoint.lat = "";
      },
      // 保存(新增)
      async onSubmit() {
        console.log(this.form);
        let param2 = {
          longitude: this.form.addrPoint.lng,
          latitude: this.form.addrPoint.lat,
          mc: this.form.attendancePoint,
          cardRange: this.form.range,
        };
        this.$loading("正在提交...");
        let res = await mapSetApi.insertDzStDevice(param2);
        if (res.success) {
          this.$messager.alert({
            title: "系统提示",
            icon: "success",
            msg: "保存成功！"
          });
          // 清空右侧填写的，加载左侧列表
          this.clearMsg();
          this.loadDataLeft();
        } else {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: res.message
          });
        }
        this.$loading.close();
      },

      // 修改
      async onModify() {
        // console.log(this.form);
        // console.log(this.selectedRowDataUp);
        let param2 = {
          bh: this.selectedRowDataUp.bh,
          longitude: this.form.addrPoint.lng,
          latitude: this.form.addrPoint.lat,
          mc: this.form.attendancePoint,
          cardRange: this.form.range,
        };
        this.$loading("正在提交...");
        let res = await mapSetApi.updateDzStDevice(param2);
        if (res.success) {
          this.$messager.alert({
            title: "系统提示",
            icon: "success",
            msg: "修改成功！"
          });
          // 清空右侧填写的，加载左侧列表
          this.clearMsg();
          this.loadDataLeft();
          this.selectedRowDataUp = null;
        } else {
          this.$messager.alert({
            title: "系统提示",
            icon: "error",
            msg: res.message
          });
        }
        this.$loading.close();
      },

      // 新增弹窗
      addPoint(){
        this.isNew = 1;
        this.btndisabledNo = 1;
        this.textBoxDisabled = false;
        this.valueChange();
      },
      // 修改弹窗
      modifyPoint(){
        if (this.selectedRowDataUp == null) {
          this.$messager.alert({
            title: "操作提示",
            icon: "warning",
            msg: "请选择要修改的考勤点!"
          });
          return;
        }
        this.isNew = 2;
        this.btndisabledNo = 1;
        this.textBoxDisabled = false;
        this.valueChange();
        // this.getRightMsg(this.selectedRowDataUp);
      },
      // 左侧删除
      async deletePoint() {
        if (this.selectedRowDataUp == null) {
          this.$messager.alert({
            title: "操作提示",
            icon: "warning",
            msg: "请选择要删除的考勤点!"
          });
          return;
        } else {
          // 删除接口
          this.$loading("正在删除...");
          let res = await mapSetApi.deleteDzStDevice({bh: this.selectedRowDataUp.bh});
          if (res.success) {
            this.$messager.alert({
              title: "系统提示",
              icon: "success",
              msg: "删除成功！"
            });
            this.loadDataLeft();
            this.selectedRowDataUp = null;
          } else {
            this.$messager.alert({
              title: "系统提示",
              icon: "error",
              msg: res.message
            });
          }
          this.$loading.close();
        }
      },
      // 左侧选择行点击行
      rowClickedd(params) {
        // console.log(params);
        this.selectedRowDataUp = {};
        this.selectedRowDataUp = params.data;
        this.textBoxDisabled = true;
        this.btndisabledNo = 2;
        // console.log(this.selectedRowDataUp);
        this.getRightMsg(this.selectedRowDataUp);
        // if (this.selectedRowDataUp.longitude !=  null && this.selectedRowDataUp.latitude != null){
        //   let rowPoint = new BMap.Point(this.selectedRowDataUp.longitude,this.selectedRowDataUp.latitude);
        //   this.map.centerAndZoom(rowPoint, 16);
        //   let newmk = new BMap.Marker(rowPoint, {enableDragging: true});
        //   this.map.addOverlay(newmk);
        // }

      },
      getRightMsg(item) {
        this.form.attendancePoint = item.mc;    //考勤点名称
        this.form.range = item.cardRange == null ? "" : item.cardRange;    //考勤范围
        if (item.longitude != null && item.latitude != null) {
          let lng = item.longitude;    //经度
          let lat = item.latitude;    //维度
          // console.log(lng,lat)
          this.form.addrPoint.lng = lng + "";
          this.form.addrPoint.lat = lat + "";
          let point = new BMap.Point(lng, lat);
          this.getAddrByPoint2(point)
        }
      },
      // 点击左侧行时只输入到右侧底部与地图展示，不查询
      getAddrByPoint2(point) {
        var that = this;
        that.map.clearOverlays();
        that.map.centerAndZoom(point);
        that.mk = new BMap.Marker(point, {enableDragging: true});
        that.map.addOverlay(that.mk);
        var geco = new BMap.Geocoder();
        geco.getLocation(point, function (res) {
          // console.log(res);    //当前位置信息
          that.mk.setPosition(point);
          that.map.panTo(point);
          that.form.address = "";
          // that.form.addrPoint.lng = point.lng + "";
          // that.form.addrPoint.lat = point.lat + "";
          // that.form.addrPoint = point;
          // that.InOrOutPolygon(point.lng, point.lat);
        });
        //创建圆打卡范围
        that.greatCircle(point);
      },
      // 按下回车事件，触发查询
      searchEnter() {
        if (event.which === 13) {
          this.loadDataLeft();
        }
      },
      onGridReady(params) {
        this.gridApi = params.api;
        this.columnApi = params.columnApi;
        // 调整表格列宽大小自适应
        // this.gridApi.sizeColumnsToFit();

      },
      newlink(){
        window.open("http://localhost:8000/")
      },


    }
  }
</script>

<style lang="scss" scoped>

</style>

